package front

import (
	"encoding/json"
	red "github.com/gomodule/redigo/redis"
	"github.com/juju/errors"
	"qihuang/config"
	"qihuang/db/mysql"
	"qihuang/db/redis"
	"qihuang/loger"
	"qihuang/model"
	"qihuang/protocol"
	"strconv"
	"time"
	//"reflect"
)

type ArticleParams struct {
	CategoryId int    `json:"category_id"`
	Title      string `json:"title"`
	Summary    string `json:"summary"`
	Content    string `json:"content"`
	Keywords   string `json:"keywords"`
	Cover      string `json:"cover"`
	FromUrl    string `json:"from_url "`
	CreateTime string `json:"create_time"`
	ModifyTime string `json:"modify_time"`
	Status     int    `json:"status"`
}

//文章详情
type ArticleDetails struct {
	model.Articles
}

type Articles struct {
}

type ArticleList struct {
	Total    int              `json:"total"`
	Datalist []model.Articles `json:"datalist"`
}

//添加文章
func (c *Articles) Add(params *ArticleParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	articles := model.Articles{
		CategoryId: params.CategoryId,
		Title:      params.Title,
		Summary:    params.Summary,
		Keywords:   params.Keywords,
		Cover:      params.Cover,
		Content:    params.Content,
		FromUrl:    params.FromUrl,
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	//articles_contents := model.ArticlesContents{
	//	ShowType: params.ShowType,
	//	Contents: params.Contents,
	//}
	//if articles_contents.GetShowTypeName() == "" {
	//	resp.Msg = "文章内容显示类型错误"
	//	return resp
	//}
	//添加articles_contents
	db := mysql.Default().GetConn()
	defer db.Close()
	// 开始事务
	tx := db.Begin()
	//添加articles
	err := db.Model(model.Articles{}).Create(&articles).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	////获取插入记录的Id
	//var article_id []int
	//db.Raw("select LAST_INSERT_ID() as id").Pluck("article_id", &article_id)
	//articles_contents.ArticleId = article_id[0]
	//err = db.Create(&articles_contents).Error
	//if err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Msg = "系统错误"
	//	tx.Rollback()
	//	return resp
	//}
	//提交事务
	tx.Commit()
	resp.Status = 0
	return resp
}

//分页获取文章列表mysql
func (c *Articles) GetListForMysql(page int, pageSize int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	articles := make([]model.Articles, 0)
	db = db.Where("status = ?", 0)
	//if cateId > 0 {
	//	db = db.Where("category_id = ?", cateId)
	//}
	if err := db.Select(fields).Offset(offset).Limit(pageSize).Order("id desc").Find(&articles).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	resp.Status = 0
	resp.Data = articles
	return resp
}

//分页获取文章列表mysql
func (c *Articles) GetListByIdsForMysql(page int, pageSize int, ids []int) []model.Articles {
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	articles := make([]model.Articles, 0)
	db = db.Where("status = ?", 0)
	//if cateId > 0 {
	//	db = db.Where("category_id = ?", cateId)
	//}
	if err := db.Where("id IN (?)", ids).Offset(offset).Limit(pageSize).Order("id desc").Find(&articles).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return articles
	}
	return articles
}

//分页获取文章列表es
func (c *Articles) GetListForEs(page int, pageSize int, cateId int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	//esclient, err := es.Default()
	//if err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Status = -999
	//	resp.Msg = "系统错误"
	//	return resp
	//}
	//esconn := esclient.GetConn()
	//ctx := context.Background()
	articles := make([]model.Articles, 0)

	db := mysql.Default().GetConn()
	defer db.Close()
	offSet := pageSize * (page - 1)
	if err := db.Limit(pageSize).Offset(offSet).Where("category_id = ?", cateId).Find(&articles).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Status = 1
		resp.Msg = "系统错误"
		return resp
	}
	//
	//query := esconn.Search().
	//	Index("myblog").
	//	Type("mb_articles").
	//	Size(page_size).
	//	From((page-1)*page_size).
	//	Sort("modify_time", false).
	//	Pretty(true)
	//boolQuery := elastic.NewBoolQuery()
	//searchQuery := boolQuery.Must(elastic.NewTermQuery("status", 1))
	//if cate_id > 0 {
	//	searchQuery = searchQuery.Filter(elastic.NewTermQuery("cate_id", cate_id))
	//}
	//query = query.Query(searchQuery)
	//result, err := query.Do(ctx)
	//if err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Status = -999
	//	resp.Msg = "系统错误"
	//	return resp
	//}
	//var typ model.Articles
	////for _, item := range result.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
	//for _, item := range result.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
	//	t := item.(model.Articles)
	//	t.ModifyTime = helper.DateToDateTime(t.ModifyTime)
	//	t.CreateTime = helper.DateToDateTime(t.CreateTime)
	//	articles = append(articles, t)
	//
	//}
	resp.Status = 0
	resp.Data = articles
	return resp
}

//获取文章详情
func (c *Articles) GetArticleDetail(articleId int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	//articleContent := model.ArticlesContents{}
	articleDetails := ArticleDetails{}
	redisConn := redis.RedisClient.Pool.Get()
	cacheKey := "article_" + config.Configs.RedisCacheVersion + ":" + strconv.Itoa(articleId)
	if err := redisConn.Err(); err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	} else {
		cateCache, err := red.String(redisConn.Do("GET", cacheKey))
		if err != nil {
			loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		} else {
			if cateCache != "" {
				err := json.Unmarshal([]byte(cateCache), &articleDetails)
				if err != nil {
					loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
				}
				resp.Status = 0
				resp.Data = articleDetails
				return resp
			}
		}
	}

	db := mysql.Default().GetConn()
	defer db.Close()
	if err := db.Where("id = ?", articleId).Where("status = ?", 0).First(&articleDetails).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "文章不存在"
		return resp
	}
	if articleDetails.Id <= 0 {
		resp.Msg = "文章不存在"
		return resp
	}
	//if err := db.Where("article_id = ?", articleId).First(&articleContent).Error; err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Msg = "系统错误"
	//	return resp
	//}
	resp.Status = 0
	//articleDetails.Contents = articleContent.Contents
	//articleDetails.ShowType = articleContent.ShowType
	cacheData, err := json.Marshal(articleDetails)
	if err == nil {
		redisConn.Do("set", cacheKey, string(cacheData))
		redisConn.Do("expire", cacheKey, 86400*3)
	}
	resp.Data = articleDetails
	return resp
}

//获取文章类型
func (c *Articles) GetArticleCate() (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	redisConn := redis.RedisClient.Pool.Get()
	cacheKey := "article_cates_" + config.Configs.RedisCacheVersion
	if err := redisConn.Err(); err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	} else {
		cateCache, err := red.String(redisConn.Do("GET", cacheKey))
		if err != nil {
			loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		} else {
			if cateCache != "" {
				articleCates := make([]model.ArticlesCategory, 0)
				err := json.Unmarshal([]byte(cateCache), &articleCates)
				if err != nil {
					loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
				}
				resp.Status = 0
				resp.Data = articleCates
				return resp
			}
		}
	}

	articleCates, err := c.articleCate()
	if err != nil {
		resp.Msg = "系统错误"
		return resp
	}

	if len(articleCates) > 0 {
		cacheData, err := json.Marshal(articleCates)
		if err == nil {
			redisConn.Do("set", cacheKey, string(cacheData))
			redisConn.Do("expire", cacheKey, 86400*3)
		}

	}

	resp.Status = 0
	resp.Data = articleCates
	return resp
}

func (c *Articles) articleCate() ([]model.ArticlesCategory, error) {
	articleCates := make([]model.ArticlesCategory, 0)
	db := mysql.Default().GetConn()
	defer db.Close()
	if err := db.Order("orderby asc").Find(&articleCates).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return nil, err
	}
	return articleCates, nil
}
